<?php

class LoginForm extends CFormModel {

    public $name;
    public $pwd;
    public $rememberMe;
    public $verify;
    private $_identity;

    public function rules() {
        return array(
            array('name', 'required', 'message' => '<i class="icon-remove"></i>&nbsp;用户名必须填写'),
            array('pwd', 'required', 'message' => '<i class="icon-remove"></i>&nbsp;密码必须填写'),
            array('verify', 'required', 'message' => '<i class="icon-remove"></i>&nbsp;验证码必须填写'),
            array('verify', 'captcha', 'message' => '<i class="icon-remove"></i>&nbsp;验证码错误'),
            array('rememberMe', 'boolean'),
            array('pwd', 'authenticate'),
            
        );
    }

  
    public function authenticate($attribute, $params) {
        if (!$this->hasErrors()) {
            $this->_identity = new UserIdentity($this->name, $this->pwd);
            if (!$this->_identity->authenticate())
                $this->addError('pwd', '<i class="icon-remove"></i>&nbsp;用户名或者密码不正确');
        }
    }

    public function login() {
        if ($this->_identity === null) {
            $this->_identity = new UserIdentity($this->name, $this->pwd);
            $this->_identity->authenticate();
        }
        if ($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
            $duration = $this->rememberMe ? 3600 * 24 * 30 : 0; // 30 days
            Yii::app()->user->login($this->_identity, $duration);
            return true;
        } else
            return false;
    }

}
